package com.hdq.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.hdq.constant.JwtClaimsConstant;
import com.hdq.constant.MessageConstant;
import com.hdq.context.BaseContext;
import com.hdq.exception.TokenExpiredException;
import com.hdq.properties.JwtProperties;
import com.hdq.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;

import java.util.Map;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌，判断token是否过期
        log.info("jwt校验:{}", token);

        boolean tokenExpired = JwtUtil.isTokenExpired(jwtProperties.getAdminSecretKey(), token);
        if(tokenExpired) {
            throw new TokenExpiredException(MessageConstant.EXPIRED_Token);
        }
//        3、解析token
        Map<String, Claim> claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Long managerId = Long.valueOf(claims.get(JwtClaimsConstant.MANAGER_ID).toString());

        // 4、校验redis的token
        String redis_token = (String) redisTemplate.opsForHash().get(JwtClaimsConstant.TOKEN,managerId);
        if (token == null || !token.equals(redis_token)) {
            throw new TokenExpiredException(MessageConstant.EXPIRED_Token);
        }


        BaseContext.setCurrentId(managerId);
        log.info("当前管理员id：{}", managerId);
        //3、通过，放行
        return true;
    }

}